import React, { useEffect, useState, useContext } from 'react';
import { Button, Spin, Table, Tooltip, Divider, Modal, Form, Typography, Col, message } from 'antd';
import last from 'lodash/last';
import classNames from 'classnames';
import { withRouter } from 'umi';

import BizIcon from '@/components/BizIcon';
import { isSuccess } from '@/utils/request';
import If from '@/components/If';
import BottomAction from '@/components/BottomAction';
import authHelper from '@/utils/auth/helper';

import { personalIncomeTaxService } from '@/services/salaryManage/salaryCalculateService';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import {
    goToProcessApply,
    goToTaxCalculator,
    goToPersonalIncomeTaxInProcess,
    goToProcessDetail
} from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { NumberSettingInput, PercentSettingInput } from '@/pages/SalaryManage/components/NumberSettingInput';
import { PROCESS_TYPE } from '@/pages/SalaryManage/utils/processUtil';
import { amountSettingColumn, percentSettingColumn } from '@/pages/SalaryManage/utils/TableUtil';
import { insuranceFundFileProcessStatus as processStatus } from '@/pages/SalaryManage/enum';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import { TaxAmtDescription } from '@/pages/SalaryManage/components/TaxAmtDescription';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { BaseSettingContext } from '@/pages/SalaryManage/constant/BaseSettingContext'
import ProcessStatusTag from '../components/ProcessStatusTag';
import { ApproveInfoContext } from './ApproveInfoContext';
import pageStyle from './index.less';

const namespace = 'insuranceFundFileModel';
const { Text } = Typography;

// 已生效
const EFFECT_IN = 0;

const tableColumns = (operateConfig, { decimalPlaces }) => {
    const rel = [
        {
            title: '级数',
            dataIndex: 'taxLevel',
            width: 160,
            align: 'center'
        },
        {
            title: '累计预扣预缴应纳税所得额',
            dataIndex: 'ljsde',
            width: 250,
            align: 'left',
            render: (text, record) => <TaxAmtDescription record={record} decimalPlaces={decimalPlaces} />
        },
        percentSettingColumn({
            title: '预扣率',
            dataIndex: 'taxRate',
            width: 150
        }, { namespace }),
        amountSettingColumn({
            title: '速算扣除数',
            dataIndex: 'quickDeductAmt',
            width: 220
        }, { namespace })
    ];

    if (operateConfig) {
        const { onEdit, onDelete, disabled, pageModel } = operateConfig;

        rel.push({
            title: '操作',
            dataIndex: '_operate',
            width: 200,
            align: 'center',
            fixed: 'right',
            render(text, record) {
                return (
                    <AutoDivider>
                        <If condition={authHelper.checkCode('finance:salary:computation:social:tax:edit')}>
                            <Tooltip title="编辑">
                                <Button
                                    className={classNames(salaryStyle.operateIcon)}
                                    onClick={() =>
                                        onEdit({
                                            taxRateId: pageModel.id,
                                            taxRateDetailId: record.taxDetailId,
                                            ...record
                                        })
                                    }
                                    disabled={disabled}
                                >
                                    <BizIcon type="listfunction_edit_icon_default" />
                                </Button>
                            </Tooltip>
                        </If>
                        <If condition={authHelper.checkCode('finance:salary:computation:social:tax:del')}>
                            <Tooltip title="删除">
                                <Button
                                    className={classNames(salaryStyle.operateIcon)}
                                    disabled={disabled}
                                    onClick={() => onDelete(record)}
                                >
                                    <BizIcon type="DeleteIcon" />
                                </Button>
                            </Tooltip>
                        </If>
                    </AutoDivider>
                );
            }
        });
    }

    return rel;
};

const percentOption = name => ({
    validateFirst: true,
    rules: [
        {
            required: true,
            message: `请填写【${name}】`
        },
        {
            type: 'number',
            min: 0,
            message: `【${name}】不能小于0`
        },
        {
            type: 'number',
            max: 1,
            message: `【${name}】不能超过100%`
        },
        {
            type: 'number',
            message: `【${name}】输入长度不能大于12`
        }
    ]
});

const EditModal = Form.create({})(({ title, visible, onOk, onCancel, model = {}, form }) => {
    const { getFieldDecorator } = form;

    const [taxAmtValidate, setTaxAmtValidate] = useState({ result: true, validateStatus: 'success', help: null });

    const getValidateTaxAmtInfo = () => {
        const { taxStartAmt, taxEndAmt } = form.getFieldsValue();

        if (taxStartAmt == null || String(taxStartAmt) === '') {
            return {
                result: false,
                validateStatus: 'error',
                help: '请填写起始金额'
            };
        }

        // 起始金额大于结束金额都没有填写时
        if (taxStartAmt && taxEndAmt && taxStartAmt >= taxEndAmt) {
            return {
                result: false,
                validateStatus: 'error',
                help: '右边数额需大于左边数额'
            };
        }

        return {
            result: true,
            validateStatus: 'success',
            help: null
        };
    };

    const validateTaxAmt = (delay = true) => {
        if (delay) {
            setTimeout(() => {
                setTaxAmtValidate(getValidateTaxAmtInfo());
            }, 0);
        } else {
            setTaxAmtValidate(getValidateTaxAmtInfo());
        }
    };

    const doOk = () => {
        form.validateFields((errors, values) => {
            let hasError = false;

            // 自定义校验
            const taxAmtInfo = getValidateTaxAmtInfo();
            if (!taxAmtInfo.result) {
                hasError = true;
                validateTaxAmt();
            }

            if (errors) {
                hasError = true;
            }

            if (hasError) {
                return;
            }

            onOk({ ...model, ...values });
        });
    };

    return (
        <Modal
            visible={visible}
            title={title}
            okText="确定"
            cancelText="取消"
            onOk={doOk}
            onCancel={onCancel}
            wrapClassName={pageStyle.editModalBox}
        >
            <div className="modal-box">
                <div style={{ marginTop: '16px', marginBottom: '16px' }}>
                    <Text type="secondary">*仅支持以下内容进行编辑</Text>
                </div>

                <Form layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
                    <Form.Item
                        label={
                            <span className="multi-line-label">
                                累计预扣预缴
                                <br />
                                应纳税所得额(X):
                            </span>
                        }
                        colon={false}
                        validateStatus={taxAmtValidate.validateStatus}
                        help={taxAmtValidate.help}
                    >
                        <Col span={9}>
                            {getFieldDecorator('taxStartAmt', {
                                initialValue: model.taxStartAmt
                            })(
                                <NumberSettingInput
                                    thousandsSeparator=","
                                    onChange={validateTaxAmt}
                                    onBlur={validateTaxAmt}
                                    nonNegative
                                />
                            )}
                        </Col>
                        <Col
                            span={6}
                            className={salaryStyle.textCenter}
                            style={{ display: 'flex', justifyContent: 'space-around' }}
                        >
                            <span>&lt;</span> <span>X</span> <span>&le;</span>
                        </Col>
                        <Col span={9}>
                            {getFieldDecorator('taxEndAmt', {
                                initialValue: model.taxEndAmt
                            })(
                                <NumberSettingInput
                                    thousandsSeparator=","
                                    onChange={validateTaxAmt}
                                    onBlur={validateTaxAmt}
                                    nonNegative
                                />
                            )}
                        </Col>
                    </Form.Item>
                    <Form.Item label="预扣率(%)">
                        {getFieldDecorator('taxRate', {
                            initialValue: model?.taxRate,
                            ...percentOption('预扣率')
                        })(<PercentSettingInput thousandsSeparator="," suffix="%" />)}
                    </Form.Item>
                    <Form.Item label="速算扣除数">
                        {getFieldDecorator('quickDeductAmt', {
                            initialValue: model?.quickDeductAmt,
                            rules: [
                                {
                                    required: true,
                                    message: '请填写【速算扣除数】'
                                }
                            ]
                        })(
                            <NumberSettingInput
                                thousandsSeparator=","
                                onChange={validateTaxAmt}
                                onBlur={validateTaxAmt}
                            />
                        )}
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    );
});

const PersonalIncomeTax = ({ organizationCode, location }) => {
    const [loading, setLoading] = useState(false);
    const [pageModel, setPageModel] = useState({});
    const [approveInfo, setApproveInfo] = useState({});
    const [visible, setVisible] = useState(false);
    const [editModel, setEditModel] = useState({});
    const [title, setTitle] = useState('');
    const [resetVisible, setResetVisible] = useState(false);
    const { setApproveInfo: setApproveInfoContext } = useContext(ApproveInfoContext);
    const { baseSetting: { scale: decimalPlaces } } = useContext(BaseSettingContext);

    const effect = location.query.effect ? +location.query.effect : EFFECT_IN;

    // 查询
    const search = () => {
        setLoading(true);
        const searchPromise =
            EFFECT_IN === effect
                ? personalIncomeTaxService.queryPersonalIncomeTax({ organizationCode })
                : personalIncomeTaxService.queryPersonalIncomeTaxEffect({ organizationCode });

        searchPromise
            .then(searchResponse => {
                setLoading(false);
                if (isSuccess(searchResponse)) {
                    setPageModel(searchResponse.data);
                } else {
                    message.error(searchResponse.msg);
                }
            })
            .catch(() => {
                setLoading(false);
            });
    };

    // 保存编辑
    const saveEdit = params => {
        setLoading(true);
        const isNew = !params?.taxRateDetailId;
        const savePromise = isNew
            ? personalIncomeTaxService.addLevel(params)
            : personalIncomeTaxService.updateLevel(params);

        savePromise
            .then(saveResponse => {
                setLoading(false);

                if (isSuccess(saveResponse)) {
                    search();
                    setVisible(false);
                } else {
                    message.error(saveResponse.msg);
                }
            })
            .catch(() => {
                setLoading(false);
                setVisible(false);
            });
    };

    const onAdd = () => {
        setVisible(true);
        setTitle('添加级数');
        const lastRecord = last(pageModel?.tableData) || {};
        setEditModel({ taxRateId: pageModel.id, taxStartAmt: lastRecord.taxEndAmt });
    };

    const onEdit = record => {
        setVisible(true);
        setTitle('编辑');
        setEditModel({ ...record });
    };

    const onDelete = record => {
        Modal.confirm({
            content: <>您确定要删除【<TaxAmtDescription record={record} decimalPlaces={decimalPlaces}/>】这个级数吗？</>,
            okText: '确定',
            cancelText: '取消',
            onOk() {
                setLoading(true);
                personalIncomeTaxService
                    .deleteLevel({ taxRateId: pageModel.id, taxDetailId: record.taxDetailId })
                    .then(response => {
                        if (isSuccess(response)) {
                            search();
                        } else {
                            message.error(response.msg);
                        }
                        setLoading(false);
                    })
                    .catch(() => {
                        setLoading(false);
                    });
            }
        });
    };

    // 是否可编辑
    const resetAble = () => !!pageModel?.resetAble;
    // 是否可进入下一步
    const nextAble = () => !!pageModel?.nextAble;

    const reset = () => {
        setResetVisible(true);
    };
    const doReset = () => {
        setLoading(true);
        personalIncomeTaxService
            .resetPersonalIncomeTax({ taxRateId: pageModel?.id })
            .then(response => {
                if (!isSuccess(response)) {
                    message.warn(response.msg);
                    return;
                }
                setResetVisible(false);
                message.success('重置成功！');
                search();
            })
            .finally(() => {
                setLoading(false);
            });
    };
    const onNext = async () => {
        setLoading(true);
        personalIncomeTaxService.queryTaxLevelContinuity({ taxRateId: pageModel?.id })
            .then(response => {
                setLoading(false);
                if (!isSuccess(response)) {
                    message.error(response.msg);
                    return;
                }
                goToProcessApply(
                    PROCESS_TYPE.SALARY_SET_TAX_APPLY,
                    { taxRateId: pageModel?.id },
                    '没有找到分类为【财务个税档案流程】的流程，请先配置流程'
                );
            }).catch(response => {
                setLoading(false);
                message.error(response.msg)
            })
    };

    useEffect(
        () => {
            if (organizationCode) {
                search()
            }
        },
        [organizationCode]
    );

    useEffect(() => {
        if (pageModel?.id) {
            personalIncomeTaxService.queryTaxApproveInfo({ taxRateId: pageModel.id }).then(response => {
                if (isSuccess(response)) {
                    setApproveInfo(response.data);
                    if (EFFECT_IN !== effect) {
                        // 设置流程信息，【个税待生效档案】有用到
                        setApproveInfoContext(response.data);
                    }
                }
            });
        }
    }, [pageModel]);

    return (
        <Spin spinning={loading}>
            <div className={classNames(pageStyle.header)}>
                <TwoColHead
                    right={
                        <>
                            {EFFECT_IN === effect ? (
                                <>
                                    <Button
                                        type="link"
                                        className={salaryStyle.linkBtn}
                                        onClick={() => goToPersonalIncomeTaxInProcess(organizationCode)}
                                    >
                                        待生效档案
                                    </Button>
                                    <Divider type="vertical" style={{ marginLeft: '8px' }} />
                                </>
                            ) : null}

                            <Button
                                type="link"
                                className={classNames(salaryStyle.linkBtn, salaryStyle.ml0)}
                                onClick={() =>
                                    goToProcessDetail({
                                        processDefinitionId: approveInfo?.processDefinitionId,
                                        processInstanceId: approveInfo?.processId
                                    })
                                }
                                disabled={!(approveInfo.processDefinitionId && approveInfo.processId)}
                            >
                                查看审批详情
                            </Button>
                        </>
                    }
                    style={{ marginTop: '0' }}
                />

                <div className={pageStyle.title}>
                    <header className={pageStyle.h1}>
                        {pageModel.name}
                        <ProcessStatusTag
                            status={pageModel?.processStatus}
                            className={salaryStyle.ml8}
                            style={{ position: 'absolute', top: '3px' }}
                        />
                    </header>

                    <If condition={!!pageModel?.applyObject}>
                        <header className={pageStyle.h2}>{pageModel?.applyObject}</header>
                    </If>

                    <If condition={EFFECT_IN === effect}>
                        <div className={classNames(pageStyle.rightButtonBox)}>
                            <Tooltip title="个税计算器">
                                <Button
                                    className={salaryStyle.squareIconBtn}
                                    onClick={() => goToTaxCalculator({
                                        taxRateId: pageModel.id,
                                        name: pageModel.name,
                                        organizationCode
                                    })}
                                >
                                    <span className="iconfont iconformfunction_sync_icon_default1" />
                                </Button>
                            </Tooltip>
                        </div>
                    </If>
                </div>
            </div>
            <div>
                <Table
                    columns={tableColumns(
                        EFFECT_IN === effect
                            ? {
                                onEdit,
                                onDelete,
                                disabled: processStatus.APPROVING === pageModel?.processStatus,
                                pageModel
                            }
                            : null,
                        {
                            decimalPlaces
                        }
                    )}
                    rowKey="taxLevel"
                    dataSource={pageModel?.tableData}
                    pagination={false}
                    scroll={{ x: 'max-content' }}
                />
            </div>

            <If condition={EFFECT_IN === effect}>
                <Button
                    type="dashed"
                    block
                    className={classNames(pageStyle.addLevel)}
                    onClick={onAdd}
                    disabled={processStatus.APPROVING === pageModel?.processStatus}
                >
                    +添加级数
                </Button>

                <BottomAction>
                    <Button onClick={reset} disabled={!resetAble()}>
                        重置
                    </Button>
                    <Button type="primary" onClick={onNext} disabled={!nextAble()}>
                        下一步
                    </Button>
                    <Modal
                        visible={resetVisible}
                        title="重置"
                        okText="确定"
                        cancelText="取消"
                        onOk={doReset}
                        onCancel={() => setResetVisible(false)}
                        width={480}
                        centered
                    >
                        <div style={{ margin: '30px 20px' }}>
                            重置后所有数据将回退到上次审批通过的结果，是否确定重置？
                        </div>
                    </Modal>
                </BottomAction>
            </If>
            <If condition={visible}>
                <EditModal
                    title={title}
                    visible={visible}
                    model={editModel}
                    onOk={saveEdit}
                    onCancel={() => setVisible(false)}
                />
            </If>
        </Spin>
    );
};

export default withRouter(PersonalIncomeTax);
